package com.loe.mvp.ext_app

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Color
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.view.*
import android.view.inputmethod.InputMethodManager
import androidx.annotation.RequiresPermission
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.loe.mvp.R
import com.loe.mvp.ext_java.safe
import com.loe.mvp.util.SystemToast
import org.json.JSONObject
import java.io.Serializable

//fun Context?.start(cls: Class<*>, delay: Long = 0): XIntent
//{
//    val intent = if (Activity::class.java.isAssignableFrom(cls))
//    {
//        XIntent(this, cls)
//    } else
//    {
//        XIntent(this, FragmentPathActivity::class.java).apply()
//        {
//            putExtra("fragClass", cls.name)
//        }
//    }
//    delay(delay)
//    {
//        if (intent.onResult == null)
//        {
//            this?.startActivity(intent)
//        } else
//        {
//            if (this is androidx.fragment.app.FragmentActivity) ResultUtil.startResult(this, intent, intent.onResult)
//        }
//        if (this is Activity)
//        {
//            if (intent.isFinish) finish()
//            intent.onAfter?.invoke(this)
//        }
//    }
//
//    return intent
//}

fun Intent.putExtras(map: Map<String, Any>): Intent
{
    map.forEach()
    {
        when (it.value::class)
        {
            String::class ->
            {
                putExtra(it.key, it.value as String)
            }
            Int::class ->
            {
                putExtra(it.key, it.value as Int)
            }
            Long::class ->
            {
                putExtra(it.key, it.value as Long)
            }
            Boolean::class ->
            {
                putExtra(it.key, it.value as Boolean)
            }
            Double::class ->
            {
                putExtra(it.key, it.value as Double)
            }
            else ->
            {
                safe { putExtra(it.key, it.value as Serializable) }
            }
        }
    }
    return this
}

fun Intent.putExtras(json: JSONObject): Intent
{
    json.keys().forEach()
    { key ->
        val value = json.get(key)
        when (value::class)
        {
            String::class ->
            {
                putExtra(key, value as String)
            }
            Int::class ->
            {
                putExtra(key, value as Int)
            }
            Long::class ->
            {
                putExtra(key, value as Long)
            }
            Boolean::class ->
            {
                putExtra(key, value as Boolean)
            }
            Double::class ->
            {
                putExtra(key, value as Double)
            }
            else ->
            {
                safe { putExtra(key, value.toString()) }
            }
        }
    }
    return this
}

/**
 * 状态栏高度
 */
inline val Resources.statusHeight: Int
    get()
    {
        val resourceId = getIdentifier("status_bar_height", "dimen", "android")
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && resourceId > 0)
        {
            getDimensionPixelSize(resourceId)
        } else
        {
            0
        }
    }

/**
 * 状态栏高度
 */
inline val Context.versionName: String
    get() = try
    {
        packageManager.getPackageInfo(packageName, 0).versionName
    } catch (e: Exception)
    {
        ""
    }

/**
 * 状态栏
 */
fun Activity.setStatusAlpha(isBlack: Boolean = true)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        val window = this.window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        if (isBlack)
        {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else
        {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
    }
}

fun Activity.setStatusText(isBlack: Boolean = true)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        val window = this.window
        if (isBlack)
        {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else
        {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
    }
}

fun Activity.setStatusBar(color: Int = color(R.color.colorPrimary), isTextBlack: Boolean = false)
{
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
    {
        val window = this.window
        if (isTextBlack)
        {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else
        {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        }
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = color
    }
}

/**
 * 其他
 */
fun px(dp: Double): Int
{
    return (dp * Resources.getSystem().displayMetrics.density + 0.5).toInt()
}

fun px(dp: Int): Int
{
    return (dp * Resources.getSystem().displayMetrics.density + 0.5).toInt()
}

fun Context.color(id: Int): Int
{
    return ContextCompat.getColor(this, id)
}

fun Context.inflate(layoutId: Int, root: ViewGroup? = null): View
{
    return LayoutInflater.from(this).inflate(layoutId, root)
}

fun Context?.finish()
{
    if(this is Activity)
    {
        finish()
    }
}

fun Fragment?.finish()
{
    this?.activity?.finish()
}

fun View?.finish()
{
    this?.context?.finish()
}

inline val Context?.screenWidthDp: Int get() = this?.resources?.configuration?.screenWidthDp ?: 0
inline val Context?.screenHeightDp: Int get() = this?.resources?.configuration?.screenHeightDp ?: 0
inline val Context?.screenWidth: Int get() = px(screenWidthDp)
inline val Context?.screenHeight: Int get() = px(screenHeightDp)

fun setSystemDpi(dpi: Int = 360)
{
    val displayMetrics = Resources.getSystem().displayMetrics
    displayMetrics.densityDpi = dpi
    displayMetrics.density = displayMetrics.widthPixels * 1f / dpi
    displayMetrics.scaledDensity = displayMetrics.density
}

fun Activity?.setDpi(dpi: Int = 360)
{
    if (this != null)
    {
        val displayMetrics = resources.displayMetrics
        displayMetrics.densityDpi = dpi
        displayMetrics.density = displayMetrics.widthPixels * 1f / dpi
        displayMetrics.scaledDensity = displayMetrics.density
    }
    setSystemDpi(dpi)
}

fun Activity.hideSoft()
{
    runCatching()
    {
        val view = this.currentFocus
        val inputMethodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        view?.clearFocus()
    }
}

fun Activity.showSoft(view: View)
{
    runCatching()
    {
        view.requestFocus()
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}

/**
 * 跳转动画
 */
fun Activity?.transQuick() = this?.overridePendingTransition(R.anim.quick, R.anim.quick)

fun Activity?.transInAlpha() = this?.overridePendingTransition(R.anim.alpha_in, R.anim.on)

fun Activity?.transInScale() = this?.overridePendingTransition(R.anim.scale_in, R.anim.on)

fun Activity?.transOutScale() = this?.overridePendingTransition(R.anim.on, R.anim.scale_out)

fun Activity?.transInTop() = this?.overridePendingTransition(R.anim.slide_top_in, R.anim.on)

fun Activity?.transOutTop() = this?.overridePendingTransition(R.anim.on, R.anim.slide_top_out)

fun Activity?.transInBottom() = this?.overridePendingTransition(R.anim.slide_bottom_in, R.anim.on)

fun Activity?.transOutBottom() = this?.overridePendingTransition(R.anim.on, R.anim.slide_bottom_out)

fun Activity?.transOut() = this?.overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out)

fun Activity?.transIn() = this?.overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out)


fun Context?.showToast(o: Any?)
{
    if (this != null)
    {
        SystemToast.toast(this, "" + o)
    }
}

fun Dialog?.setOnBackListener(on: () -> Unit)
{
    this?.setOnKeyListener()
    { dialog, keyCode, event ->
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            on()
        }
        false
    }
}

/**
 * 网络状态  0: 无网络  1: 数据网络  2: wifi网络
 *
 * <uses-permission android:name="android.permission.INTERNET" />
 * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 */
inline val Context?.netState: Int
    @RequiresPermission("android.permission.ACCESS_NETWORK_STATE")
    get()
    {
        try
        {
            val manager = this!!.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                val network = manager.activeNetwork
                val networkCapabilities = manager.getNetworkCapabilities(network)
                return if (networkCapabilities!!.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))
                {
                    2
                } else
                {
                    1
                }
            } else
            {
                val networkInfo = manager.activeNetworkInfo
                return if (networkInfo!!.type == ConnectivityManager.TYPE_WIFI)
                {
                    2
                } else
                {
                    1
                }
            }
        } catch (e: Exception)
        {
        }
        return 0
    }